from datetime import datetime

from flask import Blueprint, request

from app import db
from app.models.book import Book
from app.models.book_tag import BookTag
from app.models.parent_tag import ParentTag
from app.utils.transform import row_to_dict
from app.utils.xuehuaid import IdWorker
from app.models.tag import Tag

books = Blueprint("books", __name__, url_prefix="/books")


@books.route("", methods=["POST"])
def addBooks():
    worker = IdWorker(1, 2, 0)
    bookId = worker.get_id()
    bookTitle = request.get_json()['bookTitle']
    author = request.get_json()['author']
    bookISBN = request.get_json()['bookISBN']
    publishingHouse = request.get_json()['publishingHouse']
    source = request.get_json()['source']
    description = request.get_json()['description']
    book = Book(book_id=bookId, book_title=bookTitle, author=author, bookISBN=bookISBN,
                publishing_house=publishingHouse,
                gmt_create=datetime.now(),
                gmt_modified=datetime.now(),
                source=source,
                stock=1,
                description=description,
                is_user_book=False)
    db.session.add(book)
    tags = request.get_json()['childTagId']
    for tag in tags:
        bookTag = BookTag(book_id=bookId, tag_id=tag)
        db.session.add(bookTag)
    db.session.commit()
    return {"message": "success"}


@books.route("/<key>", methods=["GET"])
def search_book(key):
    key = f'%{key}%'  # 使用 f-string 格式化字符串并加上通配符
    books = db.session.query(Book).filter(Book.book_title.like(key)).all()
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}


@books.route('/recommends', methods=['GET'])
def recommends():
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    books = db.session.query(Book).filter(Book.author == "金庸").all()
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}


@books.route('/parenttags/<parenttagId>', methods=['GET'])
def getParentTags1(parenttagId):
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    books = db.session.query(Book).join(BookTag, BookTag.book_id == Book.book_id).join(ParentTag,
                                                                                       ParentTag.tag_id == BookTag.tag_id).filter(
        ParentTag.tag_id == parenttagId).all()
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}


@books.route("", methods=["GET"])
def get_all_books():
    books = db.session.query(Book).all()
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    return {"data": results}


@books.route("/delete", methods=["PUT"])
def deleteBooks():
    id = request.get_json()['book_id']
    book = db.session.query(Book).filter(Book.book_id == id).first()
    book.stock = 0
    db.session.commit()
    return {"message": "success"}


@books.route("", methods=['PUT'])
def changeBooks():
    bookId = request.get_json()['book_id']
    bookTitle = request.get_json()['book_title']
    author = request.get_json()['author']
    bookISBN = request.get_json()['bookISBN']
    publishingHouse = request.get_json()['publishing_house']
    source = request.get_json()['source']
    description = request.get_json()['description']
    book = db.session.query(Book).filter(Book.book_id == bookId).first()
    book.book_title = bookTitle
    book.author = author
    book.publishing_house = publishingHouse
    book.source = source
    book.description = description
    book.bookISBN = bookISBN
    book.gmt_modified = datetime.now()
    db.session.commit()
    return {"message": "success"}


@books.route("/pages", methods=["GET"])
def getAllBooks():
    books = db.session.query(Book).filter(Book.stock == 1).all()
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}


@books.route('/tags/<tagId>', methods=['GET'])
def getTags1(tagId):
    page = request.args.get('page')
    page = int(page)
    per_page = request.args.get('per-page')
    per_page = int(per_page)
    books = db.session.query(Book).join(BookTag, Book.book_id == BookTag.book_id).filter(
        BookTag.tag_id == tagId).all()
    results = []
    for book in books:
        result = row_to_dict(book)
        results.append(result)
    start_index = (page - 1) * per_page
    end_index = start_index + per_page
    books = results[start_index:end_index]
    for book in books:
        bookTag = db.session.query(BookTag).join(Book, Book.book_id == BookTag.book_id).filter(
            BookTag.book_id == book["book_id"]).all()
        result1 = []
        for tag in bookTag:
            Tag1 = db.session.query(Tag).filter(Tag.tag_id == tag.tag_id).first()
            parentTagId = Tag1.parent_tag_id
            parentTagName = db.session.query(ParentTag).filter(ParentTag.tag_id == parentTagId).first().tag_name
            result = row_to_dict(Tag1)
            result["parent_tag_name"] = parentTagName
            result1.append(result)
        book["tag"] = (result1)
    return {"num": len(results), "data": books}
